package com.hitqz.robot.driver.util;

import cn.hutool.core.util.StrUtil;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.hitqz.robot.driver.communication.SerialPortServer;
import com.hitqz.robot.driver.communication.TcpClient;
import com.hitqz.robot.driver.netty.protocol.message.KcMessage;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;
import java.util.concurrent.*;

@Slf4j
public class M518Toolkit {
    public static String m518ComName = "";

    public static String m518OpenDoorText = "";

    public static String m518CloseDoorText = "";

    public static SerialPortServer m518SerialPortServer = null;

    //获取消息结果
    public static final ConcurrentHashMap<Integer, CompletableFuture<Boolean>> requestMap = new ConcurrentHashMap<>(2);

    //开门
    public static boolean openDoor(){
        if (m518SerialPortServer == null || StrUtil.isBlank(m518OpenDoorText)) {
            return false;
        }
        m518SerialPortServer.sendHexStr(m518OpenDoorText);
        return waitForResponse(1);
    }

    // 关门
    public static boolean closeDoor(){
        if (m518SerialPortServer == null || StrUtil.isBlank(m518CloseDoorText)) {
            return false;
        }
        m518SerialPortServer.sendHexStr(m518CloseDoorText);
        return waitForResponse(0);
    }

    /**
     * 等待发送结果
     * @param type 0-关门 1-开门
     * @return 是否执行成功
     */
    public static boolean waitForResponse(int type) {
        CompletableFuture<Boolean> future = new CompletableFuture<>();
        requestMap.put(type, future);
        try {
            return future.get(8, TimeUnit.SECONDS);
        } catch (InterruptedException | ExecutionException e) {
            throw new RuntimeException(e);
        } catch (TimeoutException e) {
            log.warn("[M518R] {} timeout ", type == 0 ? "关门" : "开门");
        }
        return false;
    }

    public static void release(int type) {
        CompletableFuture<Boolean> future = requestMap.remove(type);
        if (future != null) {
            future.complete(true);
            //log.debug("[kc]seq:{},cmd:{},release",kcMessage.getSequence(),kcMessage.getCmdHexStr());
        }
    }


}
